<template>
  <div class="qr-scanner-container">
    <!-- 扫码区域 -->
    <div id="reader" class="reader-container"></div>

    <!-- 扫码提示 -->
    <div class="scan-tips">
      <p v-if="!scanning" class="text-center text-gray-600 mt-4">
        点击下方按钮开始扫码
      </p>
      <p v-else class="text-center text-gray-600 mt-4">
        请将二维码对准扫描框
      </p>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <template v-if="!scanning">
        <el-button type="primary" @click="startScanning">
          开始扫码
        </el-button>
      </template>
      <template v-else>
        <el-button type="danger" @click="stopScanning">
          停止扫码
        </el-button>
      </template>
    </div>

    <!-- 扫码结果展示 -->
    <div v-if="scanStatus" class="scan-status-box">
      <div class="status-icon">
        <el-icon v-if="scanStatus === 'scanning'" class="text-primary text-2xl">
          <Loading/>
        </el-icon>
        <el-icon v-else-if="scanStatus === 'confirmed'" class="text-success text-2xl">
          <Select/>
        </el-icon>
      </div>
      <p class="status-text">
        {{ statusText[scanStatus] }}
      </p>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import {Html5Qrcode} from 'html5-qrcode'
import {Loading, Select} from '@element-plus/icons-vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/stores/user'
import {ElMessage, ElMessageBox} from "element-plus";
import request from "@/utils/request.js";

const router = useRouter()
const userStore = useUserStore()
const emit = defineEmits(['closed'])
// 扫码相关状态
const scanning = ref(false)
const scanStatus = ref('') // scanning, confirmed
const statusText = {
  scanning: '正在验证...',
  confirmed: '登录成功，正在跳转...'
}
let html5QrCode = null
// 初始化扫码器
onMounted(() => {
  html5QrCode = new Html5Qrcode("reader")
})

// 开始扫码
const startScanning = async () => {
  try {
    const qrCodeSuccessCallback = async (decodedText, decodedResult) => {
      // 停止扫码
      await stopScanning()

      // 处理扫码结果
      await handleScanResult(decodedText)
    }

    const config = {
      fps: 10,
      qrbox: {width: 250, height: 250},
      aspectRatio: 1.0
    }

    await html5QrCode.start(
        {facingMode: "environment"},
        config,
        qrCodeSuccessCallback
    )

    scanning.value = true
  } catch (err) {
    ElMessage.error('启动扫码失败，请确保已授权摄像头权限')
    console.error('扫码错误:', err)
  }
}

// 停止扫码
const stopScanning = async () => {
  if (html5QrCode && html5QrCode.isScanning) {
    try {
      await html5QrCode.stop()
      scanning.value = false
    } catch (err) {
      console.error('停止扫码错误:', err)
    }
  }
}

// 处理扫码结果
const handleScanResult = async (qrCodeData) => {
  try {
    scanStatus.value = 'scanning'
    const uuid = String(qrCodeData).replace("/user/auth/", "")
    await request.put(`${qrCodeData}/${userStore.token}`)
    // 显示确认框
    const confirmed = await ElMessageBox.confirm(
        `确认使用该二维码登录？`,
        '登录确认',
        {
          confirmButtonText: '确认登录',
          cancelButtonText: '取消',
          type: 'info',
          center: true,
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false
        }
    ).catch(() => false)
    if (!confirmed) {
      scanStatus.value = ''
      await request.put(`/user/cancel/${uuid}`)
      // 用户取消后重新开始扫码
      await startScanning()
      return
    }
    // 验证
    await request.put(`/user/confirm/${uuid}`)
    scanStatus.value = 'confirmed'
    ElMessage.success('登录成功')
    emit('closed')
  } catch (error) {
    ElMessage.error(error.message)
    scanStatus.value = ''
    // 失败后重新开始扫码
    await startScanning()
  }
}

// 组件销毁时停止扫码
onUnmounted(async () => {
  await stopScanning()
})
</script>

<style scoped>
.qr-scanner-container {
  @apply flex flex-col items-center justify-center p-4;
}

.reader-container {
  @apply w-full max-w-xs bg-gray-50 rounded-lg overflow-hidden mb-4;
  height: 300px;
}

.scan-tips {
  @apply mb-4;
}

.action-buttons {
  @apply mb-6;
}

.scan-status-box {
  @apply flex flex-col items-center;
}

.status-icon {
  @apply mb-2;
}

.status-text {
  @apply text-gray-600;
}

/* 优化扫码界面样式 */
:deep(#reader) {
  border: none !important;
}

:deep(#reader__scan_region) {
  min-width: unset !important;
  min-height: unset !important;
}

:deep(#reader__dashboard) {
  padding: 0 !important;
}

:deep(#reader__dashboard_section_csr) {
  display: none !important;
}

:deep(#reader__status_span) {
  display: none !important;
}
</style>
